# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '2278': {
        # 胜负支付 支付宝扫码 3.5% 100-3000 dwc
        # 胜负支付 支付宝H5 3.5% 100-3000 dwc
        'API_KEY': '16f555435aca44819e4b3e998cdc392d',
        'gateway': 'http://apis.shengfupay.com/apisubmit.aspx',
        'query_gateway': 'http://apis.shengfupay.com/search.aspx',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(d, key):
    s = 'parter={}&type={}&value={}&orderid={}&callbackurl={}{}'.format(d['parter'], d['type'],
                                                                        d['value'], d['orderid'],
                                                                        d['callbackurl'], key)
    return _gen_sign(s)


def gen_order_sign(d, key):
    s = 'version={}&customerid={}&total_fee={}&sdorderno={}&notifyurl={}&returnurl={}&{}'.format(
        d['version'], d['customerid'], d['total_fee'], d['sdorderno'], d['notifyurl'], d['returnurl'], key
    )
    return generate_sign(s)


def generate_query_sign(parameter, key):
    s = 'orderid={}&parter={}{}'.format(parameter['orderid'], parameter['parter'], key)
    m = hashlib.md5()
    m.update(s.encode('GB2312'))
    sign = m.hexdigest()
    return sign


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    s = 'orderid={}&opstate={}&ovalue={}{}'.format(params['orderid'], params['opstate'], params['ovalue'], key)
    m = hashlib.md5()
    m.update(s.encode('GB2312'))
    calculated_sign = m.hexdigest()
    if sign != calculated_sign:
        _LOGGER.info("shengfupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipayscan':
        return '992'
    elif service == 'alipayh5':
        return '1006'
    return '992'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('parter', app_id),
        ('type', _get_pay_type(service)),
        ('value', '%.2f' % pay_amount),
        ('orderid', str(pay.id)),
        ('callbackurl', '{}/pay/api/{}/shengfupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('agent', ''),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("shengfupay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['orderid'])
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# ok
def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("shengfupay notify data: %s, order_id is%s", data, data['orderid'])
    verify_notify_sign(data, key)
    pay_id = data['orderid']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s", data)
        raise ParamError('shengfupay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['opstate'])
    trade_no = data['sysorderid']
    total_fee = float(data['ovalue'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 0 成功， 其他失败
    if trade_status == 0:
        _LOGGER.info('shengfupay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start): p2]
    else:
        return ''


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    key = _get_api_key(app_id)
    p_dict = {
        'parter': app_id,
        'orderid': str(pay_id),
    }
    p_dict['sign'] = generate_query_sign(p_dict, key)
    url = _get_query_gateway(app_id) + '?orderid={}&parter={}&sign={}'.format(p_dict['orderid'], p_dict['parter'],
                                                                              p_dict['sign'])
    _LOGGER.info(u'shengfupay create query url : %s', url)
    _LOGGER.info(u'shengfupay create query data: %s, order_id is: %s', json.dumps(p_dict), p_dict['orderid'])
    response = requests.get(url)
    _LOGGER.info(u'shengfupay create query rsp: %s', response.text)
    if response.status_code == 200:
        trade_status = int(_get_str(response.text, 'opstate=', '&'))
        total_fee = str(_get_str(response.text, 'ovalue=', '&'))
        query_sign = str(response.text[response.text.find('sign') + 5:])
        orderid = str(_get_str(response.text, 'orderid=', '&'))
        query_resp_data = {'orderid': orderid, 'opstate': trade_status, 'ovalue': total_fee, 'sign': query_sign}
        verify_notify_sign(query_resp_data, key)
        trade_no = pay_order.third_id
        total_fee = float(total_fee)
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        # 3：请求参数无效
        # 2：签名错误
        # 1：商户订单号无效
        # 0：支付成功
        # 其他：用户还未完成支付或者支付失败
        if trade_status == 0:
            _LOGGER.info('shengfupay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('shengfupay data error, status_code: %s', response.status_code)
